import projectSetting from "@/settings/projectSetting"
import { AxiosCanceler } from '@/utils/http/axios/axiosCancel';

const { routerGuardSetting } = projectSetting;

export function setupRouterGuard(router) {
    createHttpGuard(router)
    createScrollGuard(router)
}

// 在路由切换时，先将pending状态的接口取消掉
function createHttpGuard(router) {
    let axiosCanceler
    if (routerGuardSetting.removeAllHttpPendingOnSwitch) {
        axiosCanceler = new AxiosCanceler();
    }
    router.beforeEach(async (to, from, next) => {
        if (axiosCanceler) {
            await axiosCanceler.removeAllPending();
        }
        next()
        return true
    })
}

// 在路由切换后将滚动条滚动到顶部
function createScrollGuard(router) {
    if (routerGuardSetting.scrollToTopOnSwitch) {
        const html = document.getElementsByTagName('html')[0]
        router.afterEach(async () => {
            html.scrollTo(0, 0)
            return true
        })
    }
}
